package pers.huangyuhui.sms.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: LoginFilter
 * @Description: 拦截用户未登录状态下的所有.do请求
 * @author: tea
 */
//@WebFilter( filterName = "loginFilter" ,
//			urlPatterns = {"*.do"})
//			urlPatterns = { "/toMainView.do",
//							"/toStudentListView.do",
//							"/toTeacherListView.do",
//							"/toClassListView.do",
//							"/toPersonalView.do"})
public class LoginFilter implements Filter {

	public LoginFilter() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

//		System.out.println(httpServletRequest.getRequestURI());
		String filterUrl = httpServletRequest.getRequestURI();
		// 把验证码的请求放行掉,否则验证码无法正确显示……
		// 同理,放行登陆的请求……
		System.out.println("已拦截请求: " + filterUrl);
		if (filterUrl.equals("/sms_war_exploded/generateVerificationCode.do") || filterUrl.equals("/sms_war_exploded/loginController/login.do")) {
			System.out.println("放行请求: " + filterUrl);
			chain.doFilter(request, response);
			return;
		}

		// 判断用户是否已经登录
		Object user = httpServletRequest.getSession().getAttribute("userInfo");
		if (user == null) {
			// httpServletRequest.getRequestDispatcher("/view/login.jsp").forward(httpServletRequest,httpServletResponse);
//			String url = "/sms_war_exploded/";
			String url = "";
			// 这里使用 正则表达式 匹配 url 中的前两个 "/"
			String path = "^/[^/]+/";
			java.util.regex.Pattern p = java.util.regex.Pattern.compile(path);
			java.util.regex.Matcher m = p.matcher(filterUrl);
			// 如果匹配上了, url 就是/**/这样的字符串……
			// 不可能匹配不上,没匹配上就是路径本身有问题……
			// eg:有类似 /sms_war_exploded/studentController/getStudentList.do 的请求
			// url 就是 /sms_war_exploded/
			if (m.find()) {
				url = m.group();
			}
//			System.out.println(url);
			httpServletResponse.sendRedirect(url + "index.jsp");
			return;
		}

		System.out.println("用户已登录,放行请求: " + filterUrl);
		chain.doFilter(request, response);

	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
